package com.train.course.service.impl;

import com.train.course.domain.CommentLike;
import com.train.course.mapper.CommentLikeMapper;
import com.train.course.mapper.VideoCommentMapper;
import com.train.course.service.ICommentLikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 评论点赞 服务实现
 */
@Service
public class CommentLikeServiceImpl implements ICommentLikeService {

    @Autowired
    private CommentLikeMapper commentLikeMapper;

    @Autowired
    private VideoCommentMapper videoCommentMapper;

    @Override
    @Transactional
    public boolean likeComment(Long userId, Long commentId) {
        // 是否已点赞
        CommentLike existing = commentLikeMapper.selectCommentLikeByUserAndComment(userId, commentId);
        if (existing != null) {
            return false;
        }

        // 插入点赞记录
        CommentLike like = new CommentLike();
        like.setUserId(userId);
        like.setCommentId(commentId);
        like.setCreateBy(String.valueOf(userId));
        like.setCreateTime(new Date());
        int inserted = commentLikeMapper.insertCommentLike(like);
        if (inserted <= 0) {
            return false;
        }

        // 增加评论点赞数
        int updated = videoCommentMapper.incrementLikeCount(commentId);
        return updated > 0;
    }

    @Override
    @Transactional
    public boolean unlikeComment(Long userId, Long commentId) {
        // 删除点赞记录
        int deleted = commentLikeMapper.deleteCommentLikeByUserAndComment(userId, commentId);
        if (deleted <= 0) {
            return false;
        }

        // 减少评论点赞数
        int updated = videoCommentMapper.decrementLikeCount(commentId);
        return updated > 0;
    }

    @Override
    public boolean isLiked(Long userId, Long commentId) {
        CommentLike existing = commentLikeMapper.selectCommentLikeByUserAndComment(userId, commentId);
        return existing != null;
    }
}
